package com.zxq.uart.service.impl;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
import com.zxq.factory.FastFrame;
import com.zxq.uart.frame.UartFrame;
import com.zxq.uart.model.PlatformAttachDTO;
import com.zxq.uart.result.CodeEnum;
import com.zxq.uart.result.ResultVO;
import com.zxq.uart.service.IPlatformExchange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;


@Slf4j
public abstract class PlatformExchange<T extends PlatformAttachDTO ,K  extends PlatformAttachDTO> implements IPlatformExchange<T,K> {


    /**
     * mqtt服务注入
     */
    @Autowired
    DeviceExchange mqttExchange;


    /**
     * 平台发送数据到设备，设备直接解析成数据回复
     * @param order 发送的数据模型
     * @return
     */
    @Override
    public ResultVO<K> exchange(T order) {
        UartFrame uartFrame = new UartFrame();
        uartFrame.setCmd(getCmd());
        uartFrame.setSession_id("000000000000");
        uartFrame.setData(order);
        byte[] post = uartFrame.encoder();
        //System.out.println("post:" + HexBin.encode(post));
        log.info("下发指令==>devId:{},order:{},frame:{}",order.getDevId(),order, HexBin.encode(post));
        byte[] msg =  mqttExchange.exchange(order.getDevId(),post);
        if(msg != null) {
            K result = getResult();
            result.setDevId(order.getDevId());
            UartFrame resultFrame = new UartFrame();
            resultFrame.setData(result);
            FastFrame.decoder(resultFrame, msg);
            return new ResultVO(result);
        }
        return new ResultVO(CodeEnum.SOCKET_TIMEOUT);
    }

    public abstract Integer getCmd();

    public abstract K getResult();





}
